#!/bin/bash

# ========== 默认参数 ==========
ENV="dev"
VERSION="v1.0"
REGISTRY=""
NAMESPACE="seata520"
APP_NAME="user"

# ========== 参数解析 ==========
while [[ "$#" -gt 0 ]]; do
    case $1 in
        --REGISTRY=*) REGISTRY="${1#*=}";;
        --VERSION=*) VERSION="${1#*=}";;
        --APP_NAME=*) APP_NAME="${1#*=}";;
        *) echo "未知参数: $1"; exit 1;;
    esac
    shift
done



# ========== 构建镜像名称 ==========
IMAGE_NAME="${REGISTRY}/${NAMESPACE}/${APP_NAME}-image:${VERSION}"

# ========== 切换至服务源码目录 ==========
WORK_DIR=$(cd "$(dirname "$0")/../.." && pwd)
cd "${WORK_DIR}/${APP_NAME}" || {
  echo "❌ 服务目录不存在: ${WORK_DIR}/${APP_NAME}"
  exit 1
}
# ========== 显示构建信息 ==========
echo "=========================================="
echo "🚀 开始构建镜像"
#echo "🌍 环境       : ${ENV}"
echo "📦 服务名     : ${APP_NAME}"
echo "🏷️  版本      : ${VERSION}"
echo "📤 仓库地址    : ${IMAGE_NAME}"
echo "=========================================="

# ========== 删除旧镜像 ==========
if docker images -q "$IMAGE_NAME" > /dev/null 2>&1 && [ -n "$(docker images -q "$IMAGE_NAME")" ]; then
  echo "🧹 删除已有镜像 $IMAGE_NAME ..."
  docker rmi "$IMAGE_NAME"
  echo "删除完成 ✅"
else
  echo "镜像 $IMAGE_NAME 不存在，无需删除。"
fi


# ========== 构建镜像 ==========
echo "🔧 构建中..."
docker build -t "$IMAGE_NAME" .

# ========== 推送镜像 ==========
echo "📤 推送镜像到仓库: $IMAGE_NAME"
docker push "$IMAGE_NAME"

echo "✅ 镜像构建并推送完成: $IMAGE_NAME"